<script>
import { InfoCircleOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import axios from 'axios'
import JSZip from 'jszip/dist/jszip.min.js'
import saveAs from 'jszip/vendor/FileSaver.js'
import {getCurrentInstance} from "vue";
import {
  isLogin,
} from '~/logic'
import { TRequest } from '~/utils/ali/PCRequest'
import {parseUrl} from "~/utils/util";
// 主图分析
const visible = ref(false)
const visibleShow = ref(false)
const showTitle = ref('')
// 1 综合排序 2 销量排序 3 价格升序 4 价格降序
const sortType = ref('1')
// 解析location.href 的参数
const url = location.href
const paramsObj = parseUrl(url)
const dataSources = ref([])
const keywords = ref(paramsObj.q)
const minAmount = ref('')
const maxAmount = ref('')
const number = ref(2)
const searchStatus = ref(false)
const picSpan = ref(3)
const checkedList = ref([])
const onlyImg = ref(false)
const childKeywords = ref('')
const checkedImageLists = ref([])
const downloadStatus = ref('')
export default {
  name: 'MainImageAnalysis',
  components: { InfoCircleOutlined },
  emits: ['login'],
  setup(props, context) {
    const handle = () => {
      if (isLogin(context))
        visible.value = true
    }
    const __option = getCurrentInstance()?.appContext.provides.option;
    const download = async () => {
      if (isLogin({ context }, __option)) {
        if (!checkedImageLists.value.length) {
          message.error('请先选择图片!')
          return
        }
        downloadStatus.value = '准备中...'
        const zip = new JSZip()
        for (let i = 0; i < checkedImageLists.value.length; i++) {
          const item = checkedImageLists.value[i].split('#')
          downloadStatus.value = '下载图片：' + `ID_${i + 1}_${item[1]}`
          const response = await axios.get(item[0], { responseType: 'blob' })
          zip.file(`ID_${i + 1}_${item[1]}.jpg`, response.data)
        }
        downloadStatus.value = '导出中...'
        zip.generateAsync({ type: 'blob' }).then((content) => {
          saveAs(content, `${showTitle.value}.zip`)
          message.success('导出成功!')
          downloadStatus.value = ''
        })
      }
    }
    const analysis = async () => {
      if (!keywords.value) {
        message.error('请输入关键词!')
        return
      }
      searchStatus.value = true
      let sortTypeValue = 1
      const sortParams = {
        q: keywords.value,
        search_type: 'item',
      }
      let sortName = ''
      if (sortType.value === '1') {
        sortTypeValue = 1
        sortName = '综合排序'
      }
      else if (sortType.value === '2') {
        sortTypeValue = 2
        sortName = '销量排序'
      }
      else if (sortType.value === '4') {
        sortTypeValue = 4
        sortName = '价格降序'
      }
      else if (sortType.value === '5') {
        sortTypeValue = 5
        sortName = '价格升序'
      }
      let startPrice = null
      let endPrice = null
      if (minAmount.value !== '')
        startPrice = minAmount.value
      if (minAmount.value !== '')
        endPrice = maxAmount.value

      Reflect.set(dataSources, 'value', [])
      for (let i = 1; i <= number.value; i++) {
        const cacheKey = sortParams.sort + keywords.value + sortParams.filter + i
        try {

          const res = await TRequest.searchList(keywords.value, i, sortTypeValue, startPrice, endPrice)
          if (typeof res.itemsArray === 'undefined') {
            message.error('请求失败请稍后重试!')
            searchStatus.value = false
            return
          }
          dataSources.value.push(...res.itemsArray)
        } catch (e) {
          message.error('请求失败请稍后重试!')
          searchStatus.value = false
          return
        }
      }
      showTitle.value = `星察数据_主图分析(${sortName})_${keywords.value}(${dataSources.value.length}项)`
      visibleShow.value = true
      searchStatus.value = false
      Reflect.set(checkedImageLists, 'value', [])
    }

    return {
      handle,
      visible,
      visibleShow,
      showTitle,
      checkedList,
      checkedImageLists,
      downloadStatus,
      picSpan,
      sortType,
      keywords,
      minAmount,
      maxAmount,
      number,
      searchStatus,
      dataSources,
      analysis,
      onlyImg,
      download,
    }
  },
  watch: {
    checkedList: {
      handler: (val, old) => {
        if (old === undefined)
          old = []

        if (old.includes('全选') !== val.includes('全选')) {
          if (val.includes('全选'))
            checkedImageLists.value = dataSources.value.map(item => `${item.pic_path}#${item.item_id}`)
          else
            Reflect.set(checkedImageLists, 'value', [])
        }
        if (val.includes('查看小图'))
          picSpan.value = 2
        else
          picSpan.value = 3

        if (val.includes('只看图片'))
          onlyImg.value = true
        else
          onlyImg.value = false
      },
      immediate: true,
    },
  },
}
</script>

<template>
  <div style="display: inline-block" @click="handle">
    <slot name="default">
      <a-button type="primary" size="small" style="margin-left: 10px;">
        主图分析
      </a-button>
    </slot>
  </div>
  <!--  <a-modal :visible="true" /> -->
  <a-modal v-model:visible="visible" title="主图分析" :mask-closable="false" :footer="false">
    <a-spin :spinning="searchStatus">
      <div style="text-align: center;margin-bottom: 20px;">
        <div
          style="background: #eee;display: inline-block;border-radius: 10px;padding:5px 10px;font-size: 12px;color: #666;"
        >
          <InfoCircleOutlined style="padding-right: 5px;" />
          星察数据下载文件和数据仅供学习和参考，切勿私自商用造成侵权！
        </div>
      </div>
      <a-form
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-form-item label="排序">
          <a-radio-group v-model:value="sortType">
            <a-radio-button value="1">
              综合排序
            </a-radio-button>
            <a-radio-button value="2">
              销量排序
            </a-radio-button>
            <a-radio-button value="4">
              价格降序
            </a-radio-button>
            <a-radio-button value="5">
              价格升序
            </a-radio-button>
           
          </a-radio-group>
        </a-form-item>
        <a-form-item label="关键词">
          <a-input v-model:value="keywords" placeholder="请输入关键词" />
        </a-form-item>
        <a-form-item label="价格区间">
          <a-input-number v-model:value="minAmount" style="width: 120px;" placeholder="最低价" addon-after="元" />
          ~
          <a-input-number v-model:value="maxAmount" style="width: 120px;" placeholder="最高价" addon-after="元" />
        </a-form-item>
        <a-form-item label="搜索数量">
          前
          <a-input-number v-model:value="number" style="width: 100px;" placeholder="" />
          页(每页48条)
        </a-form-item>
        <a-divider />
        <div style="text-align: center;width: 80%;margin: 0 auto;">
          <a-button shape="round" block type="primary" size="large" @click="analysis">
            开始分析
          </a-button>
        </div>
      </a-form>
    </a-spin>
  </a-modal>
  <a-modal
    v-model:visible="visibleShow" class="mainImageModal" :width="1200" :mask-closable="false" :title="showTitle"
    :footer="false"
    style="min-height: 500px;"
  >
    <a-spin :spinning="downloadStatus !== ''" :tip="downloadStatus">
      <a-row type="flex" style="margin-bottom: 10px;">
        <a-col>
          <a-checkbox-group
            v-model:value="checkedList" :options="[
              '全选',
              // '只看图片',
              '查看小图',
            ]" style="margin-bottom: 10px"
          />
        </a-col>
        <a-col flex="1" style="text-align: center">
          <div
            style="background: #eee;display: inline-block;border-radius: 10px;padding:5px 10px;font-size: 12px;color: #666;"
          >
            <InfoCircleOutlined style="padding-right: 5px;" />
            星察数据下载文件和数据仅供学习和参考，切勿私自商用造成侵权！
          </div>
        </a-col>
        <a-col>
          已选中{{ checkedImageLists.length }}张图片
          <a-button type="primary" size="middle" @click="download">
            下载图片
          </a-button>
        </a-col>
      </a-row>
      <a-row :gutter="[8, 8]" style="max-height: 650px;overflow-y: auto">
        <a-col
          v-for="(item) in dataSources" :key="item.item_id" :style="{
          }" :span="picSpan"
        >
          <div
            class="item"
            :class="{
              active: checkedImageLists.includes(`${item.pic_path}#${item.item_id}`),
            }"
            @click="() => {
              if (checkedImageLists.includes(`${item.pic_path}#${item.item_id}`)){
                checkedImageLists.splice(checkedImageLists.indexOf(`${item.pic_path}#${item.item_id}`), 1)
              }
              else {
                checkedImageLists.push(`${item.pic_path}#${item.item_id}`)
              }
            }"
          >
            <a-radio :checked="checkedImageLists.includes(`${item.pic_path}#${item.item_id}`)" class="item-pic-radio" />
            <a-image
              :src="item.pic_path" :preview="false" :style="{
                height: picSpan === 3 ? '128px' : '80px',
                overflow: 'hidden',
              }"
            />
            <div v-if="picSpan === 3" style="padding: 5px;">
              <a-row type="flex">
                <a-col flex="1" style="font-size: 10px;color: #999;text-align: left">
                  价格:
                </a-col>
                <a-col style="font-size: 10px;color: #ff4d4f;">
                  {{ item.priceShow.unit + item.priceShow.price }}
                </a-col>
              </a-row>
              <a-row v-if="typeof item.realSales != 'undefined'" type="flex">
                <a-col flex="1" style="font-size: 10px;color: #999;text-align: left">
                  {{ item.realSales.indexOf('付款') > -1 ? '付款人数' : '收货人数' }}:
                </a-col>
                <a-col style="font-size: 10px;color: #444;">
                  {{ parseInt(item.realSales) + (item.realSales.indexOf('万') > -1 ? '0000' : '') }}
                </a-col>
              </a-row>
            </div>
          </div>
        </a-col>
      </a-row>
    </a-spin>
  </a-modal>
</template>

<style scoped>
.mainImageModal * {
  box-sizing: border-box;
}

.item {
  border: 1px solid #e8e8e8;
  text-align: center;
  position: relative;
  transition: all .3s;
}

.item-pic-radio {
  position: absolute;
  right: 0px;
  top: 0px;
  opacity: 0;
  transition: all .3s;
  z-index: 9;
}

.item:hover, .item.active {
  border: 1px solid #1890ff;
}

.item:hover .item-pic-radio, .item.active .item-pic-radio {
  opacity: 1;
}
</style>
